<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue';
import { sendChatMessage } from '@/services/chatService';
import { ElMessage, ElLoading } from 'element-plus';
import { marked } from 'marked';
import DOMPurify from 'dompurify';
import { useRouter } from 'vue-router';

// 获取路由实例
const router = useRouter();

// 聊天历史
const chatHistory = ref([]);
// 当前输入的消息
const inputMessage = ref('');
// 对话ID
const conversationId = ref('');
// 是否正在加载
const loading = ref(false);
// 聊天容器引用
const chatContainer = ref(null);
// 添加 lastMessageId ref
const lastMessageId = ref('');

// 添加用户消息到历史记录
const addUserMessage = (content) => {
  chatHistory.value.push({
    type: 'user',
    content,
    timestamp: new Date().toLocaleTimeString(),
  });
};

// 添加AI助手消息到历史记录
const addAssistantMessage = (content, isStreaming = false) => {
  chatHistory.value.push({
    type: 'assistant',
    content,
    timestamp: new Date().toLocaleTimeString(),
    isStreaming
  });
};

// 更新最后一条助手消息
const updateLastAssistantMessage = (content) => {
  const lastMessage = chatHistory.value[chatHistory.value.length - 1];
  if (lastMessage && lastMessage.type === 'assistant') {
    lastMessage.content = content;
    lastMessage.isStreaming = false;
  }
};

// 滚动到底部
const scrollToBottom = async () => {
  await nextTick();
  if (chatContainer.value) {
    chatContainer.value.scrollTop = chatContainer.value.scrollHeight;
  }
};

// 发送消息
const sendMessage = async () => {
  if (!inputMessage.value.trim()) {
    return;
  }

  const userQuery = inputMessage.value.trim();
  addUserMessage(userQuery);
  inputMessage.value = '';
  
  scrollToBottom();
  
  try {
    loading.value = true;
    addAssistantMessage('', true);
    
    const response = await sendChatMessage(
      userQuery,
      conversationId.value,
      {},
      'user',
      [],
      lastMessageId.value
    );
    
    const reader = response.body.getReader();
    const decoder = new TextDecoder();
    let currentMessage = '';
    let buffer = '';
    
    while (true) {
      const { done, value } = await reader.read();
      if (done) break;
      
      // 将新的数据添加到缓冲区
      buffer += decoder.decode(value, { stream: true });
      
      // 处理缓冲区中的完整行
      const lines = buffer.split('\n');
      buffer = lines.pop() || ''; // 保留最后一个不完整的行
      
      for (const line of lines) {
        if (line.trim() === '' || line.startsWith('event: ping')) continue;
        
        try {
          if (line.startsWith('data: ')) {
            const data = JSON.parse(line.substring(6));
            if (data.event === 'message') {
              currentMessage += data.answer || '';
              updateLastAssistantMessage(currentMessage);
              await scrollToBottom();
            } else if (data.event === 'message_end') {
              if (data.conversation_id) {
                conversationId.value = data.conversation_id;
              }
              if (data.message_id) {
                lastMessageId.value = data.message_id;
              }
            }
          }
        } catch (e) {
          console.error('解析消息失败:', e);
        }
      }
    }
    
    // 处理缓冲区中剩余的数据
    if (buffer) {
      try {
        if (buffer.startsWith('data: ')) {
          const data = JSON.parse(buffer.substring(6));
          if (data.event === 'message') {
            currentMessage += data.answer || '';
            updateLastAssistantMessage(currentMessage);
          }
        }
      } catch (e) {
        console.error('解析剩余消息失败:', e);
      }
    }
    
  } catch (error) {
    console.error('发送消息失败:', error);
    ElMessage.error(error.message || '消息发送失败，请重试');
    // 移除加载状态的消息
    chatHistory.value.pop();
  } finally {
    loading.value = false;
    scrollToBottom();
  }
};

// 渲染Markdown内容
const renderMarkdown = (content) => {
  // 使用DOMPurify净化HTML，防止XSS攻击
  return DOMPurify.sanitize(marked.parse(content));
};

// 返回上一页
const goBack = () => {
  router.go(-1);
};

// 初始化欢迎消息
onMounted(() => {
  addAssistantMessage(`您好！欢迎使用云慧问答，我是您的智能学习助手。

我支持各类学科知识解答、学习方法指导、作业辅导、考试复习建议等专业服务，致力于帮助您提升学习效率和成绩。
您可以直接提问，例如：

'如何提高数学解题能力？'

'英语单词记忆有什么好方法？'

'如何制定有效的学习计划？'

'物理力学公式怎么理解？'

如需帮助，请随时告诉我，智慧学习，云慧相伴。`);
  scrollToBottom();
});
</script>

<template>
  <div class="learning-chat">
    <!-- 返回按钮 -->
    <div class="back-button" @click="goBack">
      <el-icon><ArrowLeft /></el-icon>
      <span>返回</span>
    </div>

    <div class="chat-header">
      <div class="chat-title">
        <div class="logo">
          <el-icon class="learning-icon"><i class="icon-learning"></i></el-icon>
        </div>
        <h1>云慧问答</h1>
      </div>
      <div class="chat-subtitle">基于DeepSeek的智能学习助手</div>
    </div>

    <div class="chat-container" ref="chatContainer">
      <div class="chat-messages">
        <div v-for="(message, index) in chatHistory" :key="index" class="message-wrapper" :class="message.type">
          <div class="message-avatar">
            <el-avatar v-if="message.type === 'user'" :icon="'UserFilled'" class="user" />
            <el-avatar v-else :src="'/ai-avatar.png'" class="assistant" />
          </div>
          <div class="message-content">
            <div class="message-header">
              <span class="message-sender">{{ message.type === 'user' ? '您' : '云慧问答' }}</span>
              <span class="message-time">{{ message.timestamp }}</span>
            </div>
            <div class="message-body" :class="{ 'streaming': message.isStreaming }">
              <div v-if="message.isStreaming" class="typing-indicator">
                <span></span>
                <span></span>
                <span></span>
              </div>
              <div v-else v-html="renderMarkdown(message.content)" class="markdown-content"></div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="chat-input">
      <el-input
        v-model="inputMessage"
        type="textarea"
        :rows="1"
        placeholder="请输入您的学习问题..."
        resize="none"
        @keydown.enter.prevent="sendMessage"
      />
      <el-button
        type="primary"
        :icon="loading ? 'Loading' : 'Position'"
        class="send-button"
        :loading="loading"
        @click="sendMessage"
        :disabled="loading || !inputMessage.trim()"
      >
        发送
      </el-button>
    </div>
  </div>
</template>

<style scoped>
.learning-chat {
  display: flex;
  flex-direction: column;
  height: 100vh;
  width: 100%;
  background: linear-gradient(135deg, #f5f5f5 0%, #e8e8e8 100%);
  color: #333;
  font-family: Microsoft YaHei, Heiti SC, tahoma, arial, Hiragino Sans GB, "\5B8B\4F53", sans-serif;
  position: relative;
}

.back-button {
  position: fixed;
  top: 20px;
  left: 20px;
  z-index: 1000;
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 8px 12px;
  background: rgba(255, 255, 255, 0.9);
  border: 1px solid #ddd;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  color: #333;
  transition: all 0.3s ease;
  backdrop-filter: blur(10px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.back-button:hover {
  background: rgba(255, 255, 255, 1);
  border-color: #0077b6;
  color: #0077b6;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.back-button .el-icon {
  font-size: 16px;
}

.chat-header {
  padding: 20px;
  text-align: center;
  border-bottom: 1px solid #ddd;
  background: #fff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.chat-title {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 8px;
}

.logo {
  margin-right: 12px;
  font-size: 24px;
}

.icon-learning {
  display: inline-block;
  width: 24px;
  height: 24px;
  position: relative;
}

.icon-learning:before {
  content: "📚";
  font-size: 24px;
  position: absolute;
  top: -2px;
  left: 0;
}

.chat-title h1 {
  font-size: 28px;
  font-weight: 600;
  color: #333;
  margin: 0;
}

.chat-subtitle {
  font-size: 14px;
  color: #666;
}

.chat-container {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  background: #f9f9f9;
}

.chat-messages {
  max-width: 960px;
  margin: 0 auto;
}

.message-wrapper {
  display: flex;
  margin-bottom: 24px;
}

.message-wrapper.user {
  flex-direction: row-reverse;
}

.message-wrapper.user .message-content {
  margin-right: 12px;
  margin-left: 0;
}

.message-wrapper.user .message-header {
  flex-direction: row-reverse;
}

.message-wrapper.user .message-body {
  background: #0077b6;
  color: #fff;
  border-radius: 12px 2px 12px 12px;
}

.message-wrapper.assistant .message-body {
  background: #fff;
  border: 1px solid #e0e0e0;
  border-radius: 2px 12px 12px 12px;
}

.message-avatar {
  flex-shrink: 0;
}

.message-avatar .el-avatar {
  background: transparent;
  border: 1px solid #ddd;
}

.message-avatar .el-avatar.user {
  background: linear-gradient(45deg, #0077b6, #023e8a);
  border: none;
}

.message-avatar .el-avatar.assistant {
  background: transparent;
  border: none;
}

.message-content {
  flex: 1;
  margin-left: 12px;
  max-width: calc(100% - 60px);
}

.message-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 4px;
  font-size: 12px;
}

.message-sender {
  font-weight: 600;
  color: #333;
}

.message-time {
  color: #999;
}

.message-body {
  padding: 12px 16px;
  line-height: 1.6;
  word-break: break-word;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.message-body.streaming {
  padding: 16px;
  min-height: 24px;
}

.typing-indicator {
  display: flex;
  align-items: center;
}

.typing-indicator span {
  height: 8px;
  width: 8px;
  border-radius: 50%;
  background-color: #999;
  margin: 0 2px;
  animation: typing 1.4s infinite ease-in-out;
}

.typing-indicator span:nth-child(1) {
  animation-delay: 0s;
}

.typing-indicator span:nth-child(2) {
  animation-delay: 0.2s;
}

.typing-indicator span:nth-child(3) {
  animation-delay: 0.4s;
}

.markdown-content {
  color: inherit;
}

.markdown-content :deep(pre) {
  background: #f5f5f5;
  padding: 12px;
  border-radius: 4px;
  overflow-x: auto;
  border: 1px solid #e0e0e0;
}

.markdown-content :deep(code) {
  background: #f0f0f0;
  padding: 2px 4px;
  border-radius: 3px;
  font-family: monospace;
  color: #333;
}

.markdown-content :deep(p) {
  margin: 8px 0;
}

.markdown-content :deep(ul), .markdown-content :deep(ol) {
  padding-left: 20px;
}

.markdown-content :deep(blockquote) {
  border-left: 3px solid #ddd;
  padding-left: 10px;
  margin-left: 0;
  color: #666;
  background: #f9f9f9;
}

.markdown-content :deep(table) {
  border-collapse: collapse;
  width: 100%;
  margin: 10px 0;
}

.markdown-content :deep(table th), .markdown-content :deep(table td) {
  border: 1px solid #ddd;
  padding: 6px 10px;
  text-align: left;
}

.markdown-content :deep(table th) {
  background: #f5f5f5;
  font-weight: 600;
}

.chat-input {
  padding: 16px 20px;
  background: #fff;
  border-top: 1px solid #ddd;
  display: flex;
  align-items: flex-start;
  gap: 10px;
}

.chat-input :deep(.el-textarea__inner) {
  background: #fff;
  border: 1px solid #ddd;
  border-radius: 8px;
  color: #333;
  font-family: Microsoft YaHei, Heiti SC, tahoma, arial, Hiragino Sans GB, "\5B8B\4F53", sans-serif;
}

.chat-input :deep(.el-textarea__inner):focus {
  border-color: #0077b6;
  box-shadow: 0 0 0 2px rgba(0, 119, 182, 0.2);
}

.chat-input :deep(.el-textarea__inner)::placeholder {
  color: #999;
}

.send-button {
  flex-shrink: 0;
  border-radius: 6px;
  padding: 8px 16px;
  height: 40px;
  background: #0077b6;
  border: none;
  color: #fff;
  cursor: pointer;
  font-family: Microsoft YaHei, Heiti SC, tahoma, arial, Hiragino Sans GB, "\5B8B\4F53", sans-serif;
  transition: background-color 0.3s ease;
}

.send-button:hover {
  background: #023e8a;
}

.send-button:disabled {
  background: #ccc;
  cursor: not-allowed;
}

@keyframes typing {
  0% {
    transform: translateY(0px);
    opacity: 0.4;
  }
  50% {
    transform: translateY(-5px);
    opacity: 0.8;
  }
  100% {
    transform: translateY(0px);
    opacity: 0.4;
  }
}

@media (max-width: 768px) {
  .learning-chat .chat-header {
    padding: 15px;
  }
  
  .learning-chat .chat-title h1 {
    font-size: 24px;
  }
  
  .learning-chat .chat-container {
    padding: 15px;
  }
  
  .learning-chat .chat-input {
    padding: 12px 15px;
  }
  
  .learning-chat .message-content {
    max-width: calc(100% - 50px);
  }

  .back-button {
    top: 15px;
    left: 15px;
    padding: 6px 10px;
    font-size: 13px;
  }

  .back-button .el-icon {
    font-size: 14px;
  }
}
</style> 